package String;



public class p151反转字符串中的单词 {
    class Solution {
        public String reverseWords(String s) {
            int left = 0;
            int right = s.length() - 1;
            // 去掉两边的空格
            while(s.charAt(left) == ' ') left++;
            while(s.charAt(right) == ' ') right--;

            int index;
            StringBuilder sb = new StringBuilder();
            while(left <= right){
                index = right;
                // 从后向前 找到第一个完整的单词【下标从index + 1 到 right】
                while(s.charAt(index) != ' ') index--;
                for(int i = index + 1; i <= right; i++){
                    sb.append(s.charAt(i));
                }
                right = index;
                // 如果不是最后一个单词就增加空格
                if(left < right) sb.append(" ");
                // 去除单词间间隔的空格
                while (s.charAt(right) == ' ') right--;
            }
            return sb.toString();
        }
    }
}
